package cae.gui.msg;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;

import cae.gui.util.CaeJDialog;
import cae.logic.CaeMessageSender;
import cae.logic.destination.CaeDestination;
import cae.logic.destination.CaeDestinatiosManager;
import cae.logic.destination.CaeGroup;

public class CaeSendGroupDialog extends CaeJDialog implements ActionListener 
{
	private static final long serialVersionUID = 1L;
	private JPanel panel = null;
	
	private JTextArea textArea;
	private CaeGroup group;
	private static Logger logger = Logger.getLogger(CaeSendGroupDialog.class);
	
	public CaeSendGroupDialog(JFrame frame, CaeGroup group)
	{
		super(frame, "Enviar Mensaje a "+group.getNick(), true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.group = group;
		
		panel = new JPanel(new BorderLayout());
		getContentPane().add(panel);

		textArea = new JTextArea(10, 40);
		textArea.setLineWrap(true);
		panel.add(new JScrollPane(textArea), BorderLayout.CENTER);
		
		JButton sendB = new JButton("Enviar");
		sendB.addActionListener(this);
		panel.add(sendB, BorderLayout.SOUTH);
		
		pack();
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(screenSize.width / 4, screenSize.height /4);
        
		setResizable(false);
		setAlwaysOnTop(true);
		setVisible(true);
		
		// TODO FOCO
		//FocusManager.getCurrentManager().
		
	}

	public void actionPerformed(ActionEvent e)
	{
		List<String> members = group.getMembers();
		for (String destS : members)
		{
			new Thread(new SingleSender(destS)).start();
		}
		
		setVisible(false);
	}
	
	private class SingleSender implements Runnable
	{
		CaeDestination dest;
		
		private SingleSender(String destS)
		{
			dest = CaeDestinatiosManager.getInstance().getDestinationByAlias(destS);
		}
		
		public void run() 
		{
			// ES ESPERADO QUE ALGUNOS MIEMBROS DEL GRUPO NO ESTEN DISPONIBLES
			try {
				CaeMessageSender.sendMessage(textArea.getText(), dest);
			} catch (IOException e) {
				//CaeAlert.error("No se ha podido enviar el mensaje a " + dest.getAlias());
				logger.debug("No se ha podido enviar el mensaje a " + dest.getAlias());
			}
		}
	}
}

